//
//  IconViewController.m
//  oneSelect
//
//  Created by satoshi_uma on 2020/6/19.
//  Copyright © 2020 satoshi_uma. All rights reserved.
//

#import "IconViewController.h"
#import "TOCropViewController.h"

@interface IconViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, TOCropViewControllerDelegate>

@property (nonatomic, strong) UIImage *image;           // The image we'll be cropping
@property (nonatomic, strong) UIImageView *imageView;   // The image view to present the cropped image
@property (weak, nonatomic) IBOutlet UIImageView *cropImage;

@property (nonatomic, assign) TOCropViewCroppingStyle croppingStyle; //The cropping style
@property (nonatomic, assign) CGRect croppedFrame;
@property (nonatomic, assign) NSInteger angle;

@property (weak, nonatomic) IBOutlet UIButton *iosSize;
@property (weak, nonatomic) IBOutlet UILabel *sizeLabel;
@property (weak, nonatomic) IBOutlet UIView *freeSize;
@property (weak, nonatomic) IBOutlet UIView *totalSize;

@end

@implementation IconViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
}

- (IBAction)getIosSize:(UIButton *)sender {
    /// 总大小
    float totalsize = 0.0;
    /// 剩余大小
    float freesize = 0.0;
    /// 是否登录
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSDictionary *dictionary = [[NSFileManager defaultManager] attributesOfFileSystemForPath:[paths lastObject] error:&error];
    if (dictionary) {
        NSNumber *_free = [dictionary objectForKey:NSFileSystemFreeSize];
        freesize = [_free unsignedLongLongValue] * 1.0 / 1024 / 1024 / 1024;

        NSNumber *_total = [dictionary objectForKey:NSFileSystemSize];
        totalsize = [_total unsignedLongLongValue] * 1.0 / 1024 / 1024 / 1024;
        
//        [_iosSize setTitle:[NSString stringWithFormat:@"%.1fG",freesize] forState:UIControlStateNormal];
        _sizeLabel.text = [NSString stringWithFormat:@"%.1f/%.0fG",freesize,totalsize];
        
        CGFloat xishu = totalsize/_totalSize.frame.size.width;
        CGFloat freeWidth = freesize/xishu;
    
        _freeSize.frame = CGRectMake(_freeSize.frame.origin.x, _freeSize.frame.origin.y, 0, _freeSize.frame.size.height);
        
        [UIView animateWithDuration:1.0 animations:^{
            self->_freeSize.frame = CGRectMake(self->_freeSize.frame.origin.x, self->_freeSize.frame.origin.y, freeWidth, self->_freeSize.frame.size.height);
        }];
        
        //        _totalSize.frame = CGRectMake(_totalSize.frame.origin.x, _totalSize.frame.origin.y, freeWidth, _totalSize.frame.size.height);
    } else {
        NSLog(@"获取系统内存信息时出错：域 = %@, 错误码 = %ld", [error domain], (long)[error code]);
    }
}

- (IBAction)selectIcon:(UIButton *)sender {
    self.croppingStyle = TOCropViewCroppingStyleCircular;
//    self.croppingStyle = TOCropViewCroppingStyleDefault;

    UIImagePickerController *profilePicker = [[UIImagePickerController alloc] init];
    profilePicker.modalPresentationStyle = UIModalPresentationPopover;
    profilePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    profilePicker.allowsEditing = NO;
    profilePicker.delegate = self;
    profilePicker.preferredContentSize = CGSizeMake(512, 512);
    profilePicker.popoverPresentationController.barButtonItem = self.navigationItem.leftBarButtonItem;
    [self presentViewController:profilePicker animated:YES completion:nil];
}

#pragma mark - Image Picker Delegate - 系统图库代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *, id> *)info
{
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    TOCropViewController *cropController = [[TOCropViewController alloc] initWithCroppingStyle:self.croppingStyle image:image];
    cropController.delegate = self;
    {
    //如果希望通过标题标签提供额外说明，请取消注释
    //cropController.title = @"Crop Image";

    //--如果要测试恢复到以前的作物设置，请取消注释这些--
//    cropController.angle = 90; //图像旋转的初始角度
//    cropController.imageCropFrame = CGRectMake(0,0,2848,4288); //裁剪控制器将显示的初始帧。

    //--取消对以下代码行的注释，以测试纵横比特性--
//    cropController.aspectRatioPreset = TOCropViewControllerAspectRatioPresetSquare; //将初始纵横比设置为平方
//    cropController.aspectRatioLockEnabled = YES; //裁剪框已锁定为纵横比，无法调整其大小
//    cropController.resetAspectRatioEnabled = NO; //当点击“重置”时，宽高比将不会重置回默认值
//    cropController.aspectRatioPickerButtonHidden = YES;

    //--取消注释这一行代码，将工具栏放在视图控制器的顶部--
//    cropController.toolbarPosition = TOCropViewControllerToolbarPositionTop;

    //--取消对这行代码的注释，使其仅包含特定类型的预设比率
//    cropController.allowedAspectRatios = @[@(TOCropViewControllerAspectRatioPresetOriginal),
//                                           @(TOCropViewControllerAspectRatioPresetSquare),
//                                           @(TOCropViewControllerAspectRatioPreset3x2)];
//
//    cropController.rotateButtonsHidden = YES;
//    cropController.rotateClockwiseButtonHidden = NO;
//
//    cropController.doneButtonTitle = @"Title";
//    cropController.cancelButtonTitle = @"Title";

    //--取消对这行代码的注释，以在取消时显示确认对话框--
    //cropController.showCancelConfirmationDialog = YES;

    //如果希望始终显示网格，请取消注释
//    cropController.cropView.alwaysShowCroppingGrid = YES;

    //如果不希望半透明效果，请取消对此的注释
//    cropController.cropView.translucencyAlwaysHidden = YES;
    }
    self.image = image;

    //如果是profile picture，则推到同一个导航堆栈上
    if (self.croppingStyle == TOCropViewCroppingStyleCircular) {
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            [picker dismissViewControllerAnimated:YES completion:^{
                [self presentViewController:cropController animated:YES completion:nil];
            }];
        } else {
            [picker pushViewController:cropController animated:YES];
        }
    } else { //otherwise dismiss, and then present from the main controller
        [picker dismissViewControllerAnimated:YES completion:^{
            [self presentViewController:cropController animated:YES completion:nil];
            //[self.navigationController pushViewController:cropController animated:YES];
        }];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Cropper Delegate - 裁剪代理
- (void)cropViewController:(TOCropViewController *)cropViewController didCropToImage:(UIImage *)image withRect:(CGRect)cropRect angle:(NSInteger)angle
{
    self.croppedFrame = cropRect;
    self.angle = angle;
    [self updateImageViewWithImage:image fromCropViewController:cropViewController];
}

- (void)cropViewController:(TOCropViewController *)cropViewController didCropToCircularImage:(UIImage *)image withRect:(CGRect)cropRect angle:(NSInteger)angle
{
    self.croppedFrame = cropRect;
    self.angle = angle;
    [self updateImageViewWithImage:image fromCropViewController:cropViewController];
}

- (void)updateImageViewWithImage:(UIImage *)image fromCropViewController:(TOCropViewController *)cropViewController
{
    self.cropImage.image = image;
    [self layoutImageView];

//    self.navigationItem.rightBarButtonItem.enabled = YES;

    if (cropViewController.croppingStyle != TOCropViewCroppingStyleCircular) {
        
//        self.cropImage.hidden = YES;
        
        [cropViewController dismissAnimatedFromParentViewController:self
                                                   withCroppedImage:image
                                                             toView:self.cropImage
                                                            toFrame:CGRectZero
                                                              setup:^{ [self layoutImageView]; }
                                                         completion:
         ^{
//            self.cropImage.hidden = NO;
        }];
        
    } else {
        
//        self.cropImage.hidden = NO;
        NSLog(@"%@",self.cropImage.image);
        [cropViewController dismissViewControllerAnimated:YES completion:nil];
        
    }
}

- (void)layoutImageView
{
    if (self.cropImage.image == nil) return;

    CGFloat padding = 20.0f;

    CGRect viewFrame = self.view.bounds;
    viewFrame.size.width -= (padding * 2.0f);
    viewFrame.size.height -= ((padding * 2.0f));

    CGRect imageFrame = CGRectZero;
    imageFrame.size = self.cropImage.image.size;

    if (self.cropImage.image.size.width > viewFrame.size.width ||
        self.cropImage.image.size.height > viewFrame.size.height) {
        CGFloat scale = MIN(viewFrame.size.width / imageFrame.size.width, viewFrame.size.height / imageFrame.size.height);
        imageFrame.size.width *= scale;
        imageFrame.size.height *= scale;
        imageFrame.origin.x = (CGRectGetWidth(self.view.bounds) - imageFrame.size.width) * 0.5f;
        imageFrame.origin.y = (CGRectGetHeight(self.view.bounds) - imageFrame.size.height) * 0.5f;
        self.cropImage.frame = imageFrame;
    } else {
        self.cropImage.frame = imageFrame;
        self.cropImage.center = (CGPoint) { CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds) };
    }
}

@end
